package com.zoiz.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zoiz.dbutils.ThreadHolder;
import com.zoiz.plus.Execution;
import com.zoiz.plus.Interceptor;
import com.zoiz.plus.InterceptorChain;
import com.zoiz.plus.InterceptorOrder;
import com.zoiz.plus.renderer.Renderer;


/**
 * Transaction interceptor.
 */
@InterceptorOrder(1)
public class TxInterceptor implements Interceptor {
	private final Log log = LogFactory.getLog(getClass());
	public void intercept(Execution execution, InterceptorChain chain)
			throws Exception {
		try {
			if (execution.needTransaction()) {
				log.info("start current transaction");
				ThreadHolder.getCurrentConnection().setAutoCommit(false);
				try {
					chain.doInterceptor(execution);
					log.info("now commit current transaction!");
					ThreadHolder.getCurrentConnection().commit();
				} catch (Exception e) {
					e.printStackTrace();
					log.info("rollback current transaction");
					ThreadHolder.getCurrentConnection().rollback();
					throw e;
				}
			} else {
				chain.doInterceptor(execution);
			}
		} finally {
			ThreadHolder.getHolder().closeConnection();
		}
	}
}
